package com.ailot.cloud.base.data.mybatis;

import com.ailot.cloud.base.data.datascope.DataScopeHandler;
import com.ailot.cloud.base.data.datascope.DataScopeProperties;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Slf4j
@Configuration
@ConditionalOnBean(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@AllArgsConstructor
@MapperScan("com.ailot.cloud.**.mapper")
public class MybatisPlusConfig {

    private DataScopeProperties dataScopeProperties;
    private DataSource dataSource;

    /**
     * 分页、数据权限拦截
     *
     * @return MybatisPlusInterceptor
     */
    @Bean
    @ConditionalOnMissingBean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        log.info("初始化mybatis拦截器");
        DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor();
        dataPermissionInterceptor.setDataPermissionHandler(new DataScopeHandler(dataScopeProperties, dataSource));
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //数据权限拦截
        interceptor.addInnerInterceptor(dataPermissionInterceptor);
        //分页拦截
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}
